import React, { Component } from "react";
import { Modal, Button,Spin } from "antd";
import ItemStack from "../entity/ItemStack";
import ItemBox from "./ItemBox";
import { Divider } from 'antd';
import { Select } from 'antd';
const { Option } = Select;

const fs = window.require("fs");

class ItemSelector extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading:true,//加载状态
      itemList:{'minecraft':[new ItemStack()]},
      curModName:'minecraft',
      onSelectItem:props.onSelectItem,
    };
    
  }

  componentDidMount(){
    this.readItem();
  }
  componentWillReceiveProps(nextProps){
    this.readItem();
  }

  /**
   * 读取存储物品数据的json文件，并初始化ItemList
   * @param {string} fileName 
   */
  readItem=(fileName='itemsData.json')=>{
    
    //读取文件
    //不知道为啥，异步的方法时不时就会无法调用回调函数
    let data = fs.readFileSync(fileName);

    //初始化
    let itemList = {'minecraft':[new ItemStack()]};
    let jsonObject = JSON.parse(data);
    //console.log(jsonObject);
    for(let modName in jsonObject){
      //遍历每一个mod的每个物品
      itemList[modName] = itemList[modName] ?? [new ItemStack()]
      for(let itemName in jsonObject[modName]){
        itemList[modName].push(new ItemStack(modName,itemName,jsonObject[modName][itemName].texture));
      }
    }

    //设置state
    this.setState({
      loading:false,
      itemList:itemList,
    });
    
  }

  /**
   * mod下拉框回调
   * @param {*} value 
   */
  onModChange = (value)=>{
    this.setState({
      curModName:value
    })
  }

  render() {
    return (
      <Modal
        title="选择物品"
        footer={null}
        {...this.props}
      >
        <Spin spinning={this.state.loading} tip="加载物品列表中，请稍候">
          <label>mod：</label>
          
          <Select defaultValue={this.state.curModName} style={{ width: 120 }} onChange={this.onModChange}>
            {Object.keys(this.state.itemList).map((modName,index)=>{
              return (
                <Option value={modName} key={modName+index}>{modName}</Option>
              )
            })
            }
          </Select>
          <br/>
          <Divider plain>选择物品</Divider>
          {
            this.state.itemList[this.state.curModName].map((item,index)=>{
              return (
                <ItemBox key={item+index} itemStack={item} onClick={()=>this.state.onSelectItem(item)}/>
              )
            })
          }
        </Spin>
        <p>{this.state.loading}</p>
      </Modal>
    );
  }
}

export default ItemSelector;
